#!/bin/bash
function usage(){
    cat<<-EOF
	Usage: $(basename $0) OPTIONS <input file>
	Options:
	        -o <out file>
	        -h help
	EOF
    exit 1
}

del=0
while getopts ":ho:d" opt;do
    case $opt in
        h)
            usage
            ;;
        o)
            out=$OPTARG
            ;;
        d)
            del=1
            ;;
        :)
            echo "Option \"$OPTARG\" need argument"
            usage
            ;;
        \?)
            echo "Option \"$OPTARG\" not support"
            usage
    esac
done
shift $((OPTIND-1))
f=$1
if [[ -z "$f" ]];then
    echo "Need input file"
    exit 1
fi

if ! echo "$f" | grep -q '.c$';then
    echo "input file must end with .c"
    exit 1
fi

if [ -z "$out" ];then
    out=$f.go
fi

if ! command -v go >/dev/null 2>&1;then
    echo "Need go."
    exit 1
fi

GCC=
if command -v gcc >/dev/null 2>&1;then
    GCC=gcc
elif command -v clang >/dev/null 2>&1;then
    GCC=clang
else
    echo "need gcc or clang"
    exit 1
fi

$GCC -E $f > $out
sed -i.bak -e '/^#/d' $out
go fmt $out
if (($del==1));then
    rm -rf ${out}.bak
fi

(echo -e "// Note this file is created by makeType.sh\n// Don't modify it directly";cat $out)>$out.xx
mv $out.xx $out
